package com.example.maruko_course_backend.utils;

import java.util.ArrayList;
import java.util.List;

public class DisplayStringUtil {

  public static String addEnterCharForDisplay(String originStr) {
    if (originStr.length() < 10) {
      return originStr;
    }
    return addEnterCharInRightPosition(originStr);
  }

  private static String addEnterCharInRightPosition(String originStr) {
    int enterCharPosition = calEnterCharPosition(originStr);
    if (enterCharPosition == 0) {
      return originStr;
    }
    return originStr.substring(0, enterCharPosition) + StringUtil.LINE_BREAK + originStr.substring(enterCharPosition);
  }

  private static int calEnterCharPosition(String originStr) {
    int midPosition = originStr.length() / 2;
    List<Integer> allSymbolPositions = getAllSymbolPositions(originStr);
    return getMinDistancePosition(midPosition, allSymbolPositions) + 1;
  }

  private static List<Integer> getAllSymbolPositions(String originStr) {
    List<Integer> symbolPositions = new ArrayList<>();
    symbolPositions.add(originStr.indexOf("-"));
    addAllCommaPositions(originStr, symbolPositions);
    return symbolPositions;
  }

  private static void addAllCommaPositions(String originStr, List<Integer> symbolPositions) {
    if (!originStr.contains(",")) {
      return;
    }
    while(originStr.contains(",")) {
      symbolPositions.add(originStr.indexOf(","));
      originStr = originStr.replaceFirst(",", "*");
    }
  }

  private static int getMinDistancePosition(int midPosition, List<Integer> symbolPositions) {
    int result = 0;
    int minDistance = Integer.MAX_VALUE;
    for (Integer symbolPosition : symbolPositions) {
      if (Math.abs(midPosition - symbolPosition) < minDistance) {
        minDistance = Math.abs(midPosition - symbolPosition);
        result = symbolPosition;
      }
    }
    return result;
  }
}
